﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Specialized;
using EZBarTender_Wrapper.SqlExecutor;
using System.IO;
using System.Deployment.Application;
using System.Reflection;
using System.Xml;
using EZBarTender_Wrapper.Settings;
using Util;
using EZBarTender.DataAccess.DAO;

namespace EZBarTender_Wrapper
{
	public class Program
	{
		private const int SW_SHOW = 5;
		private const int SW_RESTORE = 9;

		private String _connectionString;
		private string _corpConnectionString;
		private string _xmlFileLocation;
		private string _regularFileLocation;
		private string _regularSmallFileLocation;
		private string _specialSmallFileLocation;
		private string _specialFileLocation;
		private string _smartBuyFileLocation;
		private string _smartBuySmallFileLocation;
		private string _discontinuedFileLocation;
		private string _discontinuedSmallFileLocation;
		private string _nowEvenLowerFileLocation;
		private string _1upXSignFileLocation;
		private string _1upLSignFileLocation;
		private string _1upMSignFileLocation;
		private string _1upSSignFileLocation;
		private string _2upSignFileLocation;
		private string _4upSignFileLocation;
		private string _SB1upXSignFileLocation;
		private string _SB1upLSignFileLocation;
		private string _SB1upMSignFileLocation;
		private string _SB1upSSignFileLocation;
		private string _SB2upSignFileLocation;
		private string _SB4upSignFileLocation;
		private string _catalinaFileLocation;
        private string _discoSmallFileLocation;

        private ApplicationConfig appConfig;

		[DllImport("User32")]
		private static extern int ShowWindow(int hWnd, int nCmdShow);

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
            ApplicationConfig appConfig = new ApplicationConfig(Properties.Settings.Default);

			NameValueCollection appSettings = ConfigurationManager.AppSettings;
            String labelsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "POSPlus\\labels");

            if (appConfig.UseServerLabels)
            {
                labelsFolder = appConfig.ServerLabelLocation;
            }

			Program p = new Program(
                appConfig,
				Path.Combine(labelsFolder, "regular18up.btw"),
				Path.Combine(labelsFolder, "regular32up.btw"),
				Path.Combine(labelsFolder, "special12up.btw"),
				Path.Combine(labelsFolder, "special6up.btw"),
				Path.Combine(labelsFolder, "smartbuy6up.btw"),
                Path.Combine(labelsFolder, "smartbuy12up.btw"),
				Path.Combine(labelsFolder, "disco18up.btw"),
				Path.Combine(labelsFolder, "disco32up.btw"),
				Path.Combine(labelsFolder, "disco6up.btw"),
				Path.Combine(labelsFolder, "xl1upsign.btw"),
				Path.Combine(labelsFolder, "l1upsign.btw"),
				Path.Combine(labelsFolder, "m1upsign.btw"),
				Path.Combine(labelsFolder, "s1upsign.btw"),
				Path.Combine(labelsFolder, "2upSign.btw"),
				Path.Combine(labelsFolder, "4upSign.btw"),
				Path.Combine(labelsFolder, "xl1upsignsb.btw"),
				Path.Combine(labelsFolder, "l1upsignsb.btw"),
				Path.Combine(labelsFolder, "m1upsignsb.btw"),
				Path.Combine(labelsFolder, "s1upsignsb.btw"),
                Path.Combine(labelsFolder, "2upsignsb.btw"),
				Path.Combine(labelsFolder, "4upsignsb.btw"),
				Path.Combine(labelsFolder, "catalina12up.btw"),
                Path.Combine(labelsFolder, "disco12up.btw"));

		}

		public Program(
            ApplicationConfig appConfig,
			string regularFileLocation, 
			string regularSmallFileLocation,
			string specialSmallFileLocation,
			string specialFileLocation, 
			string smartBuyFileLocation,
			string smartBuySmallFileLocation,
			string discontinuedFileLocation,
			string discontinuedSmallFileLocation,
			string nowEvenLowerFileLocation,
			string oneUpXSignFileLocation,
			string oneUpLSignFileLocation,
			string oneUpMSignFileLocation,
			string oneUpSSignFileLocation,
			string twoUpSignFileLocation,
			string fourUpSignFileLocation,
			string SBoneUpXSignFileLocation,
			string SBoneUpLSignFileLocation,
			string SBoneUpMSignFileLocation,
			string SBoneUpSSignFileLocation,
			string SBtwoUpSignFileLocation,
			string SBfourUpSignFileLocation,
			string catalinaFileLocation,
            string discoSmallFileLocation)
        {

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                if (ApplicationDeployment.CurrentDeployment.IsFirstRun || Properties.Settings.Default.IsFirstRun)
                {
                   // MessageBox.Show("Bug Fixes:\n\n\tFixed item count discrepancies when\nprinting by modified date."
                   //         , "Release Notes", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    ShowChangesDialog();

                   // DeleteCurrentLabels();

                    //String[] dumpFiles = GetLabelsToDump();
                    //DumpFiles(dumpFiles);

                    Properties.Settings.Default.IsFirstRun = false;
                    Properties.Settings.Default.Save();
                }
            }

            _connectionString = appConfig.LocalConnectionString;
            _corpConnectionString = appConfig.CorpConnectionString;
			_regularFileLocation = regularFileLocation;
			_regularSmallFileLocation = regularSmallFileLocation;
			_specialSmallFileLocation = specialSmallFileLocation;
			_specialFileLocation = specialFileLocation;
			_smartBuyFileLocation = smartBuyFileLocation;
			_smartBuySmallFileLocation = smartBuySmallFileLocation;
			_xmlFileLocation = appConfig.PrintXml;
			_discontinuedFileLocation = discontinuedFileLocation;
			_discontinuedSmallFileLocation = discontinuedSmallFileLocation;
			_nowEvenLowerFileLocation = nowEvenLowerFileLocation;
			_1upXSignFileLocation = oneUpXSignFileLocation;
			_1upLSignFileLocation = oneUpLSignFileLocation;
			_1upMSignFileLocation = oneUpMSignFileLocation;
			_1upSSignFileLocation = oneUpSSignFileLocation;
			_2upSignFileLocation = twoUpSignFileLocation;
			_4upSignFileLocation = fourUpSignFileLocation;
			_SB1upXSignFileLocation = SBoneUpXSignFileLocation;
			_SB1upLSignFileLocation = SBoneUpLSignFileLocation;
			_SB1upMSignFileLocation = SBoneUpMSignFileLocation;
			_SB1upSSignFileLocation = SBoneUpSSignFileLocation;
			_SB2upSignFileLocation = SBtwoUpSignFileLocation;
			_SB4upSignFileLocation = SBfourUpSignFileLocation;
			_catalinaFileLocation = catalinaFileLocation;
            _discoSmallFileLocation = discoSmallFileLocation;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                CheckForShortcut();
                CreateDataDirectoryAndCopyFiles();
            }

			Application.Run(new EZBarTenderWrapper(
                appConfig,
				_regularFileLocation,
				_regularSmallFileLocation,
				_specialSmallFileLocation,
				_specialFileLocation,
				_smartBuyFileLocation,
				_smartBuySmallFileLocation,
				_discontinuedFileLocation,
				_discontinuedSmallFileLocation,
				_nowEvenLowerFileLocation,
				_1upXSignFileLocation,
				_1upLSignFileLocation,
				_1upMSignFileLocation,
				_1upSSignFileLocation,
				_2upSignFileLocation,
				_4upSignFileLocation,
				_SB1upXSignFileLocation,
				_SB1upLSignFileLocation,
				_SB1upMSignFileLocation,
				_SB1upSSignFileLocation,
				_SB2upSignFileLocation,
				_SB4upSignFileLocation,
				_catalinaFileLocation,
                _discoSmallFileLocation));
		}

        private void DeleteCurrentLabels()
        {
            String localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            String userFilePath = Path.Combine(localAppData, "POSPlus");
            String labelPath = Path.Combine(userFilePath, "labels");
            if (Directory.Exists(labelPath))
            {
                Directory.Delete(labelPath, true);         
            }
        }

        private static void CreateDataDirectoryAndCopyFiles()
        {
            String localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            String userFilePath = Path.Combine(localAppData, "POSPlus");

            if (!Directory.Exists(userFilePath))
                Directory.CreateDirectory(userFilePath);

            String imagesDirectory = Path.Combine(userFilePath, "images");
            if (!Directory.Exists(imagesDirectory))
                Directory.CreateDirectory(imagesDirectory);

            String dataImagesDirectory = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "Resources\\images");
            String[] fileNames = Directory.GetFiles(dataImagesDirectory);
            foreach (String file in fileNames)
            {
               if(!File.Exists(Path.Combine(imagesDirectory, Path.GetFileName(file))))
                    File.Copy(file, Path.Combine(imagesDirectory, Path.GetFileName(file)), true);
            }

            String labelsDirectory = Path.Combine(userFilePath, "labels");
            if (!Directory.Exists(labelsDirectory))
                Directory.CreateDirectory(labelsDirectory);

            String dataLabelsDirectory = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "Resources\\labels");
            fileNames = Directory.GetFiles(dataLabelsDirectory);
            foreach (String file in fileNames)
            {
                if (!File.Exists(Path.Combine(labelsDirectory, Path.GetFileName(file))))
                    File.Copy(file,
                        Path.Combine(labelsDirectory, Path.GetFileName(file)), true);
            }
        }

        /// <summary>
        /// This will create a Application Reference file on the users desktop
        /// if they do not already have one when the program is loaded.
        /// Check for them running the deployed version before doing this,
        /// so it doesn't kick it when you're running it from Visual Studio.
        /// </summary
        static void CheckForShortcut()
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
                if (ad.IsFirstRun)  //first time user has run the app
                {
                    Assembly code = Assembly.GetExecutingAssembly();
                    string company = string.Empty;
                    string description = string.Empty;
                    if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
                    {
                        AssemblyCompanyAttribute ascompany =
                          (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
                          typeof(AssemblyCompanyAttribute));
                        company = ascompany.Company;
                    }
                    if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
                    {
                        AssemblyDescriptionAttribute asdescription =
                          (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
                            typeof(AssemblyDescriptionAttribute));
                        description = asdescription.Description;
                    }
                    if (company != string.Empty && description != string.Empty)
                    {
                        string desktopPath = string.Empty;
                        desktopPath =
                          string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                            "\\Beta EZBarTender.appref-ms");
                        string shortcutName = string.Empty;
                        shortcutName =
                          string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),
                            "\\", company, "\\Beta EZBarTender.appref-ms");
                        System.IO.File.Copy(shortcutName, desktopPath, true);
                    }
                }
            }
        }

        private String[] GetLabelsToDump()
        {
            String dumpFile = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "Resources\\dumpfile.xml");
            XmlTextReader reader = new XmlTextReader(dumpFile);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            reader.Close();

            XmlNodeList nodes;
            XmlElement root = xmlDoc.DocumentElement;
            nodes = root.SelectNodes("/dump-files/labels/file");
            String[] files = new String[nodes.Count];
            int start = 0;
            foreach(XmlNode node in nodes)
            {
                files[start++] = Path.Combine("labels", node.Attributes["name"].Value);
            }

            return files;
        }

        private void DumpFiles(String[] files)
        {
            String localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            String userFilePath = Path.Combine(localAppData, "POSPlus");


            foreach(String file in files)
            {
                String fileDir = Path.Combine(userFilePath, file);

                if (File.Exists(fileDir))
                    File.Delete(fileDir);
            }
        }

        private void ShowChangesDialog()
        {
            Changes changes = new Changes(appConfig);
            changes.ShowDialog();
        }
	}
}
